package com.weixing.mall.provider.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.enums.OrderAppTagEnum;
import com.weixing.mall.core.enums.OrderSysTagEnum;
import com.weixing.mall.provider.api.model.vo.RoleVo;
import com.weixing.mall.provider.api.model.vo.dto.DepotRPcVo;
import com.weixing.mall.provider.api.service.DepotServiceRpc;
import com.weixing.mall.provider.api.service.ProductStockServiceRpc;
import com.weixing.mall.provider.api.service.SysUserRpcService;
import com.weixing.mall.provider.mapper.OrderBindingMapper;
import com.weixing.mall.provider.model.domain.Order;
import com.weixing.mall.provider.model.domain.OrderBinding;
import com.weixing.mall.provider.model.domain.OrderGoods;
import com.weixing.mall.provider.model.enums.AuditDeptEnum;
import com.weixing.mall.provider.model.enums.OrderFrontStateEnum;
import com.weixing.mall.provider.model.enums.OrderStateEnum;
import com.weixing.mall.provider.model.enums.ProductStatusEnum;
import com.weixing.mall.provider.model.vo.OrderDetilVo;
import com.weixing.mall.provider.service.IOrderBindingService;
import com.weixing.mall.provider.service.IOrderGoodsService;
import com.weixing.mall.provider.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单码绑定 服务实现类
 * </p>
 *
 * @author Small
 * @since 2020-04-25
 */
@Service
public class OrderBindingServiceImpl extends ServiceImpl<OrderBindingMapper, OrderBinding> implements IOrderBindingService {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderGoodsService orderGoodsService;
    @Autowired
    private SysUserRpcService sysUserRpcService;
    @Autowired
    private DepotServiceRpc depotServiceRpc;
    @Autowired
    private ProductStockServiceRpc productStockServiceRpc;
    @Override
    public String findOrderSnByCommodityCode(String commodityCode) {
        if(StrUtil.isEmpty(commodityCode)){
           return "";
        }
        OrderBinding binding=getOne(new QueryWrapper<OrderBinding>().eq("commodity_code",commodityCode));
        if(binding == null){
            return "";
        }
        Order order = orderService.getById(binding.getOrderId());
        if(order == null){
            return "";
        }
        return order.getOrderSn();
    }

    @Override
    public void cancelBindingByOrderIdOrCommodityCode(String commodityCode, Long orderId) {
        QueryWrapper<OrderBinding> queryWrapper = new QueryWrapper<>();
        if(StrUtil.isNotEmpty(commodityCode) ){
            queryWrapper.eq("commodity_code",commodityCode);
        }
        if(orderId != null){
            queryWrapper.eq("order_id",orderId);
        }
        if(StrUtil.isNotEmpty(commodityCode) || orderId != null){
            remove(queryWrapper);
        }
    }

    @Override
    public String findCommodityCodeByOrderId(Long orderId) {
        if(orderId == null){
            return null;
        }
        OrderBinding orderBinding = getOne(new LambdaQueryWrapper<OrderBinding>().eq(OrderBinding::getOrderId,orderId).last("LIMIT 1"));
        return ObjectUtil.isNotEmpty(orderBinding)?orderBinding.getCommodityCode():null;
    }

    @Override
    public OrderBinding findByOrderIdAndCode(Long orderId) {
        QueryWrapper<OrderBinding> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id",orderId);
        return getOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public void handlerUnbind(Long orderId,Long uid) {
       Order order= orderService.getById(orderId);
       Long fhyId=order.getShipperId();
        if (null == order) {
            throw  new BusinessException("订单不存在");
        }
        OrderBinding orderBinding = findByOrderIdAndCode(order.getId());
        if (null == orderBinding) {
            throw  new BusinessException("未查找到订单与商品码的绑定关系");

        }
        removeById(orderBinding.getId());//删除订单关系
        //更新订单商品二维码状态
        QueryWrapper<OrderGoods> wrapper = new QueryWrapper<OrderGoods>();
        wrapper.eq("order_id", order.getId());
        OrderGoods orderGoods = orderGoodsService.getOne(wrapper);
        orderGoods.setCommodityCode("");
        orderGoodsService.updateById(orderGoods);
        Order updateEndity=new Order();
        UpdateWrapper updateWrapper=new UpdateWrapper();
        updateWrapper.eq("id",order.getId());
       // updateWrapper.set("shipper_id",null);
       // updateWrapper.set("shipper_name",null);
       // updateWrapper.set("ship_time",null);
       // updateWrapper.set("express_sn",null);
        updateWrapper.set("audit_dept",AuditDeptEnum.DELIVERY_DEPT.getValue());//流转部门为发货阶段
        updateWrapper.set("app_tag",OrderAppTagEnum.DFH_TAG_106.getValue());
        updateWrapper.set("sys_tag", OrderSysTagEnum.DFH_TAG_108.getValue());
        updateWrapper.set("order_status",OrderStateEnum.WAIT_SHIP.getValue());//待发货状态
        updateWrapper.set("item_status",ProductStatusEnum.STATUS8.getValue());
        updateWrapper.set("front_order_status",OrderFrontStateEnum.WAIT_SHIP.getValue());

        orderService.update(updateEndity,updateWrapper);
        //库存回滚
        //获取回滚的仓库ID
        List<RoleVo> tt=sysUserRpcService.getRoleById(fhyId).getData();
        List<String> roleNames=tt.stream().map(RoleVo::getRoleCode).collect(Collectors.toList());
        String buffer=roleNames.toString();
        Long depotId =0L;
        if (buffer.contains(GlobalConstant.RoleCode.SHIPPING)) {
            Result<DepotRPcVo> outVo = depotServiceRpc.getBycode(GlobalConstant.DepotCode.FHB);
            if (outVo.isSuccess() && ObjectUtil.isNotEmpty(outVo.getData())) {
                depotId = outVo.getData().getId();
            }
        } else if (buffer.contains(GlobalConstant.RoleCode.APPYG)) {
            Result<DepotRPcVo> outVo = depotServiceRpc.getBycode(GlobalConstant.DepotCode.APP);
            if (outVo.isSuccess() && ObjectUtil.isNotEmpty(outVo.getData())) {
                depotId = outVo.getData().getId();
            }
        }
        //执行入库操作
        Result result= productStockServiceRpc.inOutStock(depotId,orderGoods.getProductId(),1,uid,order.getStockSn());
        if(!result.isSuccess()){
            throw  new BusinessException("入库失败");
        }
    }
}
